﻿<%@ WebHandler Language="C#" Class="housemgr" %>

using System;
using System.Web;
using Chenxin.Lib.Utility;
using System.Data;
using System.Text;

public class housemgr :AjaxHandlerBase
{
    public housemgr()
    {
        htTypePermit.Add("edit", Constants.Permit_HouseEdit);
    }
 
    override public void RequestProcess(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        context.Response.Buffer = true;
        context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";
        
        if (context.Request["op"] != null)
        {
            switch (context.Request["op"].ToLower())
            {
                case "gethouselist":
                    GetHouseList(context);
                    break;
                case "gethousetracelist":
                    GetHouseTraceList(context);
                    break;
                case "gethouseinfo":
                    GetHouseInfo(context);
                    break;
                case "getlist":
                    //GetList(context);
                    break;
                case "getmodel":
                    GetModel(context);
                    break;
                case "loadcommunity":
                    LoadCommunity(context);
                    break;
                case "add":
                    Add(context);
                    break;
                case "edit":
                    Edit(context);
                    break;
                case "checkprotectphone":
                    CheckProtectPhone(context);
                    break;
                case "getppclist"://获取电话保护配置列表
                    GetPPCList(context);
                    break;
                case "checkallowprivate":
                    CheckAllowPrivate(context);
                    break;
                case "checkroom":
                    CheckRoom(context);
                    break;
                case "getdatadictionary":
                    GetDataDictionary(context);
                    break;
                case "sendtoold":
                    SendToOld(context);
                    break;
                case "gethouseid":  //通过客户ID获取房源ID
                    GetHouseIdByCustomerId(context);
                    break;
                default:
                    break;
            }
        }
    }

    //推送房源回老系统
    private void SendToOld(HttpContext context)
    {
        try
        {
            string houseid = context.Request.Params["houseid"];
            string strSql = string.Format("insert into t_Exchang_House_BaseInfo(opid,HouseId,CityId,HouseCode,CommunityId,Community,BuildingId,BuildingName,Room,Address,Region,Block,CompleteYear,CustomerId,CustomerName,BuildingArea,HouseUse,BuildingType,Model_Room,CompanyId,CompanyName,Model_Hall,Model_Toilet,Model_Balcony,Total_Floor,Cur_Floor,Fitment,Direction,SalePrice_T,SalePrice_U,SalePrice_R,RentPrice,RentPrice_R,HavRentContract,PayMode,IsGroup,BaseEquip,OtherEquip,Status,Adddate,AddPersonId,AddPerson,AddDepartId,AddDepart,OprPersonId,OprPerson,OprDepartId,OprDepart,IsProtectPhone,DisplayPhone,IsProtectHouse,IsAutoProPhone,IsAutoProHouse,UpdateTime,ServiceTime,IsHot,IsHavekey,IsTrust,IsMarked,MarkCode,IsNeedTran,RequestNum,InfoSource,Actuality,BusinessKind,Property,TraceNum,HitNum,Remarks,IsHideHouse,op,optime) select newid(),HouseId,CityId,HouseCode,CommunityId,Community,BuildingId,BuildingName,Room,Address,Region,Block,CompleteYear,CustomerId,CustomerName,BuildingArea,HouseUse,BuildingType,Model_Room,CompanyId,CompanyName,Model_Hall,Model_Toilet,Model_Balcony,Total_Floor,Cur_Floor,Fitment,Direction,SalePrice_T,SalePrice_U,SalePrice_R,RentPrice,RentPrice_R,HavRentContract,PayMode,IsGroup,BaseEquip,OtherEquip,Status,Adddate,AddPersonId,AddPerson,AddDepartId,AddDepart,OprPersonId,OprPerson,OprDepartId,OprDepart,IsProtectPhone,DisplayPhone,IsProtectHouse,IsAutoProPhone,IsAutoProHouse,UpdateTime,ServiceTime,IsHot,IsHavekey,IsTrust,IsMarked,MarkCode,IsNeedTran,RequestNum,InfoSource,Actuality,BusinessKind,Property,TraceNum,HitNum,Remarks,IsHideHouse,1,getdate() from House_BaseInfo where HouseId='{0}';",houseid);
            strSql += string.Format("insert into t_Exchang_Customer_BaseInfo(opid,CustomerId,CustomerCode,CustomerName,Address,Mobile,Phone,Nationality,Sex,CertificateType,CertificateNo,DemandType,CustomerType,Status,CustomerKind,CityId,CityName,CompanyId,CompanyName,Adddate,AddPersonId,AddPerson,AddDepartId,AddDepart,OprPersonId,OprPerson,OprDepartId,OprDepart,LastTraceDay,PubLevel,op,optime) select newid(),CustomerId,CustomerCode,CustomerName,Address,Mobile,Phone,Nationality,Sex,CertificateType,CertificateNo,DemandType,CustomerType,Status,CustomerKind,CityId,CityName,CompanyId,CompanyName,Adddate,AddPersonId,AddPerson,AddDepartId,AddDepart,OprPersonId,OprPerson,OprDepartId,OprDepart,LastTraceDay,PubLevel,1,getdate() from Customer_BaseInfo where CustomerId=(select CustomerId from House_BaseInfo where HouseId='{0}')", houseid);

            Chenxin.Lib.House.DAL.House_BaseInfo.ExecuteSQL(strSql);

            context.Response.Write("{sucess:1,msg:'导回老系统成功！由于传输存在延迟，请5分钟后老系统查看！',data:''}");
        }
        catch (Exception e)
        {
            context.Response.Write("{success:0,msg:'导回老系统失败！" + e.Message + "',data:''}");
        }
    }
    

    private void GetDataDictionary(HttpContext context)
    {
        if (context.Request["datakeylist"] != null)
        {
            string strWhere = "";
            string datakeylist = context.Request["datakeylist"];
            datakeylist = datakeylist.Replace(",", "','");
            strWhere = string.Format("CompanyId = '{0}' AND ItemKey in ('{1}')", CurrentUserInfo.CompanyId, datakeylist);
            System.Collections.Generic.List<Chenxin.Lib.House.Entity.DataDictionary> dicList = null;
            dicList = Chenxin.Lib.House.DAL.DataDictionary.GetListArray(strWhere, "ItemKey asc,ItemIndex desc");

            System.Text.StringBuilder str = new System.Text.StringBuilder();
            str.Append("{");
            string tk = "";
            foreach (Chenxin.Lib.House.Entity.DataDictionary item in dicList)
            {
                if (tk != item.ItemKey)
                {
                    tk = item.ItemKey;
                    if (str.Length > 1)
                    {
                        str.Remove(str.Length - 1, 1);
                        str.Append("],");
                    }
                    str.Append(tk.Replace(".","") + ":[");
                }

                str.Append("{ txt: '" + item.ItemValue.Trim() + "', val: '" + item.ItemIndex + "',id:'" + item.RecordId + "'},");
            }
            if (str.Length > 1)
            {
                str.Remove(str.Length - 1, 1);
                str.Append("]");
            }
            str.Append("}");
            context.Response.Write("{success:1,msg:'',data:" + str.ToString() + "}");
        }
       
    }
    
    /// <summary>
    /// 获取电话保护配置列表
    /// </summary>
    /// <param name="context"></param>
    private void GetPPCList(HttpContext context)
    {
        try
        {
            StringBuilder strWhere = new StringBuilder();
            strWhere.AppendFormat(" CityId='{0}'", CurrentUserInfo.CityId);
            strWhere.AppendFormat(" and CompanyId='{0}'", CurrentUserInfo.CompanyId);
            DataSet ds = Chenxin.Lib.House.DAL.ProtectedPhoneConfig.GetList(strWhere.ToString());

            context.Response.Write("{sucess:1,msg:'',data:{" + JsonHelp.Convert2Json(ds).Replace("rows","ppc") + "}}");
        }
        catch (Exception e)
        {
            context.Response.Write("{success:0,msg:'获取配置失败！"+e.Message+"',data:''}");
        }
    }
    

    /// <summary>
    /// 验证房间号
    /// </summary>
    /// <param name="context"></param>
    private void CheckRoom(HttpContext context)
    {
        try
        {
            if (context.Request["communityid"] != null && context.Request["buildingid"] != null)
            {
                string where = string.Format(" CommunityId='{0}' and BuildingId='{1}' and CompanyId='{2}' AND Status >-10 ", context.Request["communityid"], context.Request["buildingid"], CurrentUserInfo.CompanyId);

                if (context.Request["room"] != null)
                {
                    where += string.Format(" and Room='{0}' ", context.Request["room"]);
                }

                Chenxin.Lib.House.Entity.House_BaseInfo model = Chenxin.Lib.House.DAL.House_BaseInfo.GetModel(where);
                if (model != null)
                {
                    context.Response.Write("{success:1,msg:'',data:{exist:true,model:" + JsonHelp.Convert2Json(model) + "}}");
                }
                else
                {
                    context.Response.Write("{success:1,msg:'',data:{exist:false}}");
                }
            }
            else
            {
                context.Response.Write("{success:1,msg:'',data:{exist:true}}");
            }
        }
        catch(Exception e)
        {
            context.Response.Write("{success:1,msg:'',data:{exist:true}}");            
        }
    }

    /// <summary>
    /// 检查是否允许添加（修改）公盘或私盘
    /// </summary>
    /// <param name="context"></param>
    private void CheckAllowPrivate(HttpContext context)
    {
        bool allow = false;

        //取得部门信息
        Chenxin.Lib.House.Entity.House_BusinessSetting settings = null;

        string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPART_SETTINGS, CurrentUserInfo.DepartId);
        Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
        settings = cs.GetObject<Chenxin.Lib.House.Entity.House_BusinessSetting>(strCachKey);
        if (!cs.Hit)
        {
            settings = Chenxin.Lib.House.DAL.House_BusinessSetting.GetModel(CurrentUserInfo.DepartId);
            if (settings != null) cs.Set(strCachKey, settings, DateTime.Now.AddDays(1));
        }
        if (settings != null)
        {
            allow = settings.AllowPrivHouse;
        }

        context.Response.Write(string.Format("{{success:1,msg:'',data:{{allowPrivate:{0}}}}}", allow.ToString().ToLower()));
    }

    /// <summary>
    /// 编辑
    /// </summary>
    /// <param name="context"></param>
    private void Edit(HttpContext context)
    {
        try
        {
            if (context.Request["model"] != null)
            {
                Chenxin.Lib.House.Entity.House_BaseInfo model = (Chenxin.Lib.House.Entity.House_BaseInfo)JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.House_BaseInfo));

                Chenxin.Lib.House.Entity.Community_BaseInfo entity = Chenxin.Lib.House.DAL.Community_BaseInfo.GetModel(model.CommunityId);
                Chenxin.Lib.House.Entity.Community_BuildingInfo entityBuilding = Chenxin.Lib.House.DAL.Community_BuildingInfo.GetModel(model.BuildingId);
                
                if (entity == null)
                {
                    context.Response.Write("{success:'0',msg:'获取楼盘信息失败！',data:''}");
                    return;
                }

                if (entityBuilding == null)
                {
                    context.Response.Write("{success:'0',msg:'获取楼栋信息失败！',data:''}");
                    return;
                }
                
                model.UpdateTime = DateTime.Now;
                model.ServiceTime = DateTime.Now;
                if (string.IsNullOrEmpty(model.Room))
                {
                    model.Room = "";
                }

                model.Community = entity.CommunityName;
                model.Address = entity.Address;
                model.DetailAddress = entity.Address + entityBuilding.BuildingName + model.Room;
                model.BuildingName = entityBuilding.BuildingName;
                
                model.Region = entity.Region;
                model.Block = entity.Block;
                model.HouseBlock = entity.CommunityBlock;
                
                if (model.BusinessKind == 20)
                {
                    model.SalePrice_U = model.RentPrice;
                }
                else
                {
                    model.SalePrice_U = model.SalePrice_T / model.BuildingArea;
                }
                //检查能不能更改重要字段
                Chenxin.Lib.House.Entity.House_BaseInfo housebaseinfo = Chenxin.Lib.House.DAL.House_BaseInfo.GetModel(model.HouseId);
                if (housebaseinfo==null)
                {
                    context.Response.Write("{success:'0',msg:'房源信息不存在，获取信息失败！',data:''}");
                    return;
                }
                if (!model.Status.Equals(housebaseinfo.Status) || !model.DisplayPhone.Equals(housebaseinfo.DisplayPhone) || !model.IsProtectHouse.Equals(housebaseinfo.IsProtectHouse))
                {
                    if (!checkKeyWords(housebaseinfo, Convert.ToInt32(model.Status)))
                    {
                        context.Response.Write("{success:'0',msg:'您没有更改房源关键信息的权限，请与管理员联系！',data:''}");
                        return;
                    } 
                }
                //记录状态更改
                if (!model.Status.Equals(housebaseinfo.Status))
                {
                    Chenxin.Lib.House.Entity.ChangeLog log = new Chenxin.Lib.House.Entity.ChangeLog();
                    log.RecordId = Guid.NewGuid();
                    log.HouseId = housebaseinfo.HouseId;
                    log.OperaterCode = CurrentUserInfo.UserCode;
                    log.HouseCode = model.HouseCode;
                    log.HouseAddress = model.DetailAddress;
                    log.ChangTime = DateTime.Now;
                    log.Operater = CurrentUserInfo.UserName;
                    log.OperaterId = CurrentUserInfo.UserId;
                    log.OprDepartId = CurrentUserInfo.DepartId;
                    log.OprDepart = CurrentUserInfo.DepartName;
                    log.OprCompanyId = CurrentUserInfo.CompanyId;
                    log.OprCompany = CurrentUserInfo.CompanyName;
                    log.OprCityId = CurrentUserInfo.CityId;
                    log.OprCity = CurrentUserInfo.CityName;
                    log.SourceState = housebaseinfo.Status;
                    log.TargetState	=model.Status;
                    log.OprType	="房源修改";
                    Chenxin.Lib.House.DAL.ChangeLog.Add(log);
                }
                Chenxin.Lib.House.Entity.House_TraceInfo house_TraceInfo = new Chenxin.Lib.House.Entity.House_TraceInfo();
                house_TraceInfo.TractorId = CurrentUserInfo.UserId;
                house_TraceInfo.Tractor = CurrentUserInfo.UserName;
                house_TraceInfo.Depart = CurrentUserInfo.DepartName;
                house_TraceInfo.DepartId = CurrentUserInfo.DepartId;
                house_TraceInfo.CityId = CurrentUserInfo.CityId;
                house_TraceInfo.CityName = CurrentUserInfo.CityName;
                house_TraceInfo.CompanyId = CurrentUserInfo.CompanyId;
                house_TraceInfo.CompanyName = CurrentUserInfo.CompanyName;

                Chenxin.Lib.House.BLL.House_BaseInfo.UpdateHouse(model, house_TraceInfo);

                //string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_HOUSEINFO, model.HouseId);
                //Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                //cs.Set(strCachKey, model, DateTime.Now.AddHours(1));

                //添加用户操作日志 2010-5-11 王玮 Add
                //AddLog("" + CurrentUserInfo.UserName + "更新了一个房源:" + model.Community + model.BuildingName + model.Room + "",
                //        OperationType.OperationTypeComboList()["OprType_HouseUpdate"].ToString());

                context.Response.Write(string.Format("{{success:'1',msg:'保存成功！',data:{{HouseId:'{0}'}}}}", model.HouseId));
            }
            else
            {
                context.Response.Write("{success:'0',msg:'保存失败！',data:''}");
            }
        }
        catch(Exception e)
        {
            context.Response.Write("{success:'0',msg:'"+e.Message+"',data:''}");
        }
    }

    /// <summary>
    /// 获取Model
    /// </summary>
    /// <param name="context"></param>
    private void GetModel(HttpContext context)
    {
        if (context.Request["modelid"] != null)
        {
            Chenxin.Lib.House.Entity.House_BaseInfo model = null;
            //string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_HOUSEINFO, context.Request["modelid"]);
            //Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
            //model = cs.GetObject<Chenxin.Lib.House.Entity.House_BaseInfo>(strCachKey);
            //if (!cs.Hit)
            //{
                model = Chenxin.Lib.House.DAL.House_BaseInfo.GetModel(new Guid(context.Request["modelid"]));
            //    if (model != null) cs.Set(strCachKey, model, DateTime.Now.AddHours(1));
            //}

            if (model != null)
            {
                context.Response.Write(string.Format("{{success:'1',msg:'',data:{{model:{0}}}}}", JsonHelp.Convert2Json(model)));
            }
            else
            {
                context.Response.Write("{success:'0',msg:'获取房源信息失败，房源信息不存在！',data:''}");
            }
        }
        else
        {
            context.Response.Write("{success:'0',msg:'房源记录标识丢失',data:''}");
        }
    }

    /// <summary>
    /// 验证是否需要设置保护电话
    /// </summary>
    /// <param name="context"></param>
    private void CheckProtectPhone(HttpContext context)
    {
        if (context.Request["type"] != null && context.Request["value"] != null)
        {
            string strWhere = "";
            strWhere = string.Format("and ConfigType='{0}' and ConfigMinValue<={1} and ConfigMaxValue>={1}", context.Request["type"].ToString(), context.Request["value"].ToString());
            if (Chenxin.Lib.House.DAL.ProtectedPhoneConfig.Exists(strWhere))
            {
                context.Response.Write("{success:'1',msg:'',data:{isShow:true}}");
            }
            else
            {
                context.Response.Write("{success:'1',msg:'',data:{isShow:false}}");
            }
        }
        else
        {
            context.Response.Write("{success:'0',msg:'',data:''}");
        }
    }

    /// <summary>
    ///添加
    /// </summary>
    /// <param name="context"></param>
    private void Add(HttpContext context)
    {
        try
        {
            if (context.Request["model"] != null)
            {
                Chenxin.Lib.House.Entity.House_BaseInfo model = (Chenxin.Lib.House.Entity.House_BaseInfo)JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.House_BaseInfo));
                model.HouseId = Guid.NewGuid();
                model.Adddate = DateTime.Now;
                model.AddPerson = CurrentUserInfo.UserName;
                model.AddPersonId = CurrentUserInfo.UserId;
                model.AddDepart = CurrentUserInfo.DepartName;
                model.AddDepartId = CurrentUserInfo.DepartId;
                model.OprDepart = CurrentUserInfo.DepartName;
                model.OprDepartId = CurrentUserInfo.DepartId;
                model.OprPerson = CurrentUserInfo.UserName;
                model.OprPersonId = CurrentUserInfo.UserId;
                model.CityId = CurrentUserInfo.CityId;
                model.UpdateTime = DateTime.Now;
                model.ServiceTime = DateTime.Now;
                model.CompanyId = CurrentUserInfo.CompanyId;
                model.CompanyName = CurrentUserInfo.CompanyName;
                model.IsHideHouse = false;
                if (string.IsNullOrEmpty(model.Room)) {
                    model.Room = "";
                }
                model.DetailAddress = model.Address + model.BuildingName + model.Room;
                if (model.BusinessKind == 20)
                {
                    model.SalePrice_U = model.RentPrice;
                }
                else {
                    model.SalePrice_U = model.SalePrice_T/model.BuildingArea;
                }
                
                Chenxin.Lib.House.Entity.Customer_BaseInfo customerBaseInfo = (Chenxin.Lib.House.Entity.Customer_BaseInfo)JsonHelp.Convert2Entity(context.Request["customermodel"], typeof(Chenxin.Lib.House.Entity.Customer_BaseInfo));

                customerBaseInfo.CustomerId = Guid.NewGuid(); 

                customerBaseInfo.Adddate = DateTime.Now;             //建档日期

                customerBaseInfo.CompanyId = CurrentUserInfo.CompanyId;
                customerBaseInfo.CompanyName = CurrentUserInfo.CompanyName;
                customerBaseInfo.AddPersonId = CurrentUserInfo.UserId;      //所属经纪人Id      GUID
                customerBaseInfo.AddPerson = CurrentUserInfo.UserName;               //所属经纪人
                customerBaseInfo.AddDepartId = CurrentUserInfo.DepartId;   //属经纪人部门Id    GUID
                customerBaseInfo.AddDepart = CurrentUserInfo.DepartName;               //所属经纪人部门
                customerBaseInfo.OprPersonId = CurrentUserInfo.UserId;      //操作经纪人Id      GUID
                customerBaseInfo.OprPerson = CurrentUserInfo.UserName;               //操作经纪        
                customerBaseInfo.OprDepartId = CurrentUserInfo.DepartId;   //操作经纪人部门Id  GUID
                customerBaseInfo.OprDepart = CurrentUserInfo.DepartName;               //操作经纪人部门
                customerBaseInfo.LastTraceDay = DateTime.Now; //最后跟进日期
                //hejifeng 2010-05-18 Add Start
                customerBaseInfo.CustomerKind = 10;
                //hejifeng 2010-05-18 Add End
                //hejifeng 2010-05-19 Add Start
                customerBaseInfo.CityId = CurrentUserInfo.CityId;
                customerBaseInfo.CityName = CurrentUserInfo.CityName;
                //hejifeng 2010-05-19 Add End

                //wang.wei 2010-6-23 Add
                customerBaseInfo.PubLevel = 0;
                
                if (Chenxin.Lib.House.BLL.House_BaseInfo.Add(model, customerBaseInfo))
                {
                    //添加用户操作日志 2010-5-11 王玮 Add
                    AddLog("" + CurrentUserInfo.UserName + "添加了一个房源:" + model.Community + model.BuildingName + model.Room + "",
                            OperationType.OperationTypeComboList()["OprType_HouseAdd"].ToString());
                    
                    context.Response.Write(string.Format("{{success:'1',msg:'添加成功！',data:{{HouseId:'{0}',HouseCode:'{1}'}}}}", model.HouseId, model.HouseCode));
                }
                else
                {
                    context.Response.Write(string.Format("{{success:'0',msg:'添加失败，这条房源已经存在！',data:{{HouseId:'{0}'}}}}", model.HouseId));
                }
            }
            else
            {
                context.Response.Write("{success:'0',msg:'添加失败！',data:''}");
            }

            if (!string.IsNullOrEmpty(context.Request["houseid"]))
            {
                Chenxin.Lib.House.Entity.House_PublicDatum house_PublicDatum = Chenxin.Lib.House.DAL.House_PublicDatum.GetModel(new Guid(context.Request["houseid"]));
                if (house_PublicDatum != null)
                {
                    house_PublicDatum.IsTransformed = true;
                    Chenxin.Lib.House.DAL.House_PublicDatum.Update(house_PublicDatum);
                }
            }
            
        }
        catch(Exception wrong)
        {
            context.Response.Write("{success:'0',msg:'添加失败！原因：" + wrong.Message.Replace("'","\'") + "',data:''}");          
        }
    }
    
    /// <summary>
    /// 根据拼音字母或者文字，查询符合条件的楼盘
    /// </summary>
    /// <param name="context"></param>
    private void LoadCommunity(HttpContext context)
    {
        Guid departId = CurrentUserInfo.DepartId;
        string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPART_SETTINGS, departId);
        Chenxin.Lib.House.Entity.House_BusinessSetting setting = null;

        Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
        setting = cs.GetObject<Chenxin.Lib.House.Entity.House_BusinessSetting>(strCachKey);
        if (!cs.Hit)
        {
            setting = Chenxin.Lib.House.DAL.House_BusinessSetting.GetModel(departId);
            if (setting != null) cs.Set(strCachKey, setting);
        }
        
        string strCitys ="";

        if (setting != null)
        {
            if (!string.IsNullOrEmpty(setting.CanAddAtCityId)) strCitys = setting.CanAddAtCityId;
        }

        if (strCitys == "") strCitys = CurrentUserInfo.CityId.ToString();

        System.Text.StringBuilder sbwhere = new System.Text.StringBuilder();
        
        string[] aryCity = strCitys.Split(new char[]{','});
        foreach (string strCityId in aryCity)
        {
            if (string.IsNullOrEmpty(strCityId)) continue;
            if (sbwhere.Length == 0)
                sbwhere.AppendFormat("((CityId = '{0}')", strCityId);
            else
                sbwhere.AppendFormat(" OR (CityId = '{0}')", strCityId);
        }
        if (sbwhere.Length > 0) sbwhere.Append(")");

        if (sbwhere.Length >0) 
            sbwhere.Append(" AND (Status=1) ");
        else
            sbwhere.Append(" (Status=1) ");
        
        if (context.Request["query"] != null)
        {
            sbwhere.AppendFormat(" AND (CommunityName like '%{0}%' OR Py like '%{0}%') ", context.Request["query"]);

            DataTable dt = Chenxin.Lib.House.DAL.Community_BaseInfo.GetList(sbwhere.ToString(),"CommunityName desc",30).Tables[0];

            System.Text.StringBuilder sugestionSb = new System.Text.StringBuilder();
            
            foreach (DataRow dr in dt.Rows)
            {
                sugestionSb.AppendFormat("'{0}',", dr["CommunityName"]);
            }
            context.Response.Write(string.Format("{{query:'{0}',suggestions:[{1}],{2}}}", context.Request["query"], sugestionSb.Length > 0 ? sugestionSb.Remove(sugestionSb.Length - 1, 1).ToString() : sugestionSb.ToString(), JsonHelp.Convert2Json(dt).Replace("\"rows\"","data")));
        }
    }


    /// <summary>
    /// 返回房源列表；
    /// 根据查询参数生成查询条件1,根据权限设定生成查询条件2；
    /// 返回Json数据：{count:'30',data:'abc'}
    /// </summary>
    /// <param name="context"></param>
    private void GetHouseList(HttpContext context)
    {
        string responseJson ="";
        try
        {
            int iPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1:int.Parse(context.Request["pageindex"]) +1;//页码
            int iPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30:int.Parse(context.Request["pagesize"]);//页记录数
            string strCommunity = context.Request["community"];//楼盘
            string strCommunityId = context.Request["communityid"];//楼盘
            string strRegion = context.Request["region"];//区域；
            string strBlock = context.Request["block"];//板块
            int iStatus = string.IsNullOrEmpty(context.Request["status"]) ? 1000: int.Parse(context.Request["status"]);//房源状态
            int iBussines = string.IsNullOrEmpty(context.Request["business"])? 1000:int.Parse(context.Request["business"]);//交易类型
            string strHouseUse = context.Request["houseuse"];//房屋用途
            string strBuildingType = context.Request["buildingtype"];//建筑类型
            string strLowPrice = context.Request["lowprice"];//最低价
            string strHightPrice = context.Request["heightprice"];//最高价
            string strKeyword = context.Request["keyword"];//智能
            string strUserCode = context.Request["usercode"];//工号
            string strDayType = context.Request["daytype"];//日期类型
            string strDayBegin = context.Request["daybegin"];//开始日期
            string strDayEnd = context.Request["dayend"];//结束日期
            string strOrderField = context.Request["sort"];//排序字段名
            
            string isPhoneProtected = context.Request["protected"];
            string isMarked = context.Request["marked"];
            string buildingName = context.Request["BuildingName"];
            string room = context.Request["Room"];
            string model_Room = context.Request["houseroom"];
            string model_Hall = context.Request["househall"];
            string buildingAreaStart = context.Request["area_start"];
            string buildingAreaEnd = context.Request["area_end"];
            string fitment = context.Request["Fitment"];
            string isHavekey = context.Request["haskey"];
            string floorStart = context.Request["floor_start"];
            string floorEnd = context.Request["floor_end"];
            string priceStyle = context.Request["pricetype"];
        
            Guid cityId = (string.IsNullOrEmpty(context.Request["cityid"])) ? Guid.Empty : new Guid(context.Request["cityid"]);
            Guid companyId = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);
            Guid areaId = (string.IsNullOrEmpty(context.Request["areaid"])) ? Guid.Empty : new Guid(context.Request["areaid"]);
            Guid departId = (string.IsNullOrEmpty(context.Request["departid"])) ? Guid.Empty : new Guid(context.Request["departid"]);
            Guid userId = (string.IsNullOrEmpty(context.Request["userid"])) ? Guid.Empty : new Guid(context.Request["userid"]);





            string fieldlist = " Cur_Floor,Total_Floor,Model_Toilet,Model_Room,Model_Hall,SalePrice_U,IsMarked, IsTrust, IsHavekey, IsHot, IsProtectPhone, Status, Region, Community, " +
                               "CommunityId, BuildingId, BuildingName, Room, BusinessKind, Kind, BuildingArea, SalePrice_T, RentPrice," +
                               "OprDepartId, OprDepart, OprPersonId, OprPerson, ServiceTime,Adddate,HouseId";

            string tablefieldlist = " Cur_Floor,Total_Floor,Model_Toilet,Model_Room,Model_Hall,SalePrice_U,IsMarked, IsTrust, IsHavekey, IsHot, IsProtectPhone, " +
                                    "case Status when '10' then '有效' when '-1' then '无效' when '30' then '封盘' else '暂缓' end as Status," +
                                    "Region, Community,case BusinessKind when '20' then '出租' when '10' then '出售' else '租售' end as BusinessKind,BusinessKind as Kind, " +
                                    "CommunityId, BuildingId, BuildingName, Room, BuildingArea, SalePrice_T, floor(RentPrice) as RentPrice ," +
                                    "OprDepartId, OprDepart, OprPersonId, OprPerson, ServiceTime,Adddate,HouseId";

            System.Text.StringBuilder sb1 = new System.Text.StringBuilder();

            //楼盘
            if (!string.IsNullOrEmpty(strCommunityId))
            {
                sb1.AppendFormat(" AND (CommunityId ='{0}')", strCommunityId);
            }
            else
            {
                if (!string.IsNullOrEmpty(strCommunity)) 
                    sb1.AppendFormat(" AND (Community Like '%{0}%')", strCommunity);
            }

            System.Text.StringBuilder sbRegion = new StringBuilder();
            bool bHaveRegion = false;
            //区域
            if (!string.IsNullOrEmpty(strRegion))
            {
                bHaveRegion = true;
                string[] str = strRegion.Split(',');
                sbRegion.AppendFormat(" AND ((");
                for (int i = 0; i < str.Length; i++)
                {
                    if (string.IsNullOrEmpty(str[i]))
                        continue;
                    if (i == 0)
                    {
                        sbRegion.AppendFormat(" Region = '{0}' ", str[i]);
                    }
                    else
                    {
                        sbRegion.AppendFormat(" OR Region = '{0}' ", str[i]);
                    }
                }
                sbRegion.AppendFormat(" ) ");
            }
            //板块
            if (!string.IsNullOrEmpty(strBlock))
            {
                string[] str = strBlock.Split(',');
                if (sbRegion.Length >0)
                    sbRegion.AppendFormat(" OR (");
                else
                    sbRegion.AppendFormat(" AND (");
                
                for (int i = 0; i < str.Length; i++)
                {
                    if (string.IsNullOrEmpty(str[i]))
                        continue;
                    if (i == 0)
                    {
                        sbRegion.AppendFormat(" Block = '{0}' ", str[i]);
                    }
                    else
                    {
                        sbRegion.AppendFormat(" OR Block = '{0}' ", str[i]);
                    }
                }
                sbRegion.AppendFormat(" ) ");
                
            }

            if (bHaveRegion) sbRegion.AppendFormat(" ) ");
            if (sbRegion.Length > 0) sb1.Append(sbRegion.ToString());
            //状态
            if (iStatus != 1000)
                sb1.AppendFormat(" AND (Status = {0})", iStatus);
            else
                sb1.Append(" AND (Status > -10 AND Status <30)");
            //交易
            if (iBussines != 1000)
                sb1.AppendFormat(" AND (BusinessKind = {0} OR BusinessKind = 30)", iBussines);
            //智能
            if (!string.IsNullOrEmpty(strKeyword))
            {
                string[] keyList;
                if (strKeyword.IndexOf(" ") != -1)
                {
                    keyList = strKeyword.Split(' ');
                }
                else
                {
                    keyList = strKeyword.Split(',');
                }
                StringBuilder _key = new StringBuilder();
                foreach(string tkey in keyList)
                {
                    _key.AppendFormat(" or (DetailAddress Like '%{0}%' Or HouseCode Like '%{0}%' or Community Like '%{0}%')", tkey);
                }
                sb1.AppendFormat(" and (1=0 {0})", _key);
                //sb1.AppendFormat(" AND (DetailAddress Like '%{0}%' Or HouseCode Like '%{0}%' or Community Like '%{0}%')", strKeyword);
            }
            //号
            if (!string.IsNullOrEmpty(buildingName))
                sb1.AppendFormat(" AND (BuildingName Like '%{0}%')", buildingName);
            //室
            if (!string.IsNullOrEmpty(room))
                sb1.AppendFormat(" AND (Room='{0}')", room);
            //价格
            if (!string.IsNullOrEmpty(strLowPrice) && !string.IsNullOrEmpty(strHightPrice))
            {
                decimal lprice = Convert.ToDecimal(strLowPrice);
                decimal hprice = Convert.ToDecimal(strHightPrice);
                //总价
                if ("t_price".Equals(priceStyle))
                {
                    sb1.AppendFormat(" AND (((SalePrice_T <={0} and SalePrice_T >={1}) and BusinessKind=30) or ((SalePrice_T <={0}) and (SalePrice_T >={1}) and BusinessKind=10) or ((RentPrice<={0})  and (RentPrice>={1}) and BusinessKind=20))", hprice * 10000, lprice * 10000);
                }
                else
                {
                    sb1.AppendFormat(" AND (SalePrice_U <={0} and SalePrice_U >={1})", hprice, lprice);
                }
            }
            else if (!string.IsNullOrEmpty(strLowPrice) && string.IsNullOrEmpty(strHightPrice))
            {
                decimal lprice = Convert.ToDecimal(strLowPrice);
                //总价
                if ("t_price".Equals(priceStyle))
                {
                    sb1.AppendFormat(" AND (((SalePrice_T >={0}) and BusinessKind=30) or (SalePrice_T >={0} and BusinessKind=10) or (RentPrice>={0} and BusinessKind=20))", lprice * 10000);
                }
                else
                {
                    sb1.AppendFormat(" AND (SalePrice_U >={0})", lprice);
                }
            }
            else if (!string.IsNullOrEmpty(strHightPrice) && string.IsNullOrEmpty(strLowPrice))
            {
                decimal hprice = Convert.ToDecimal(strHightPrice);
                //总价
                if ("t_price".Equals(priceStyle))
                {
                    sb1.AppendFormat(" AND (((SalePrice_T <={0}) and BusinessKind=30) or (SalePrice_T <={0} and BusinessKind=10) or (RentPrice<={0} and BusinessKind=20))", hprice * 10000);
                }
                else
                {
                    sb1.AppendFormat(" AND (SalePrice_U <={0})", hprice);
                }
            }
            //房型
            if (!string.IsNullOrEmpty(model_Room))
            {
                string[] str = model_Room.Split(',');
                sb1.AppendFormat(" AND (");
                for (int i = 0; i < str.Length; i++)
                {
                    if (string.IsNullOrEmpty(str[i]))
                        continue;
                    if (i == 0)
                    {
                        sb1.AppendFormat(" Model_Room = '{0}' ", str[i]);
                    }
                    else
                    {
                        sb1.AppendFormat(" OR Model_Room = '{0}' ", str[i]);
                    }
                }
                sb1.AppendFormat(" ) ");
            }
              //   if (!string.IsNullOrEmpty(model_Room)){
              //       sb1.AppendFormat(" AND (Model_Room = '{0}')", model_Room);
              //   }
            if (!string.IsNullOrEmpty(model_Hall))
            {
                string[] str = model_Hall.Split(',');
                sb1.AppendFormat(" AND (");
                for (int i = 0; i < str.Length; i++)
                {
                    if (string.IsNullOrEmpty(str[i]))
                        continue;
                    if (i == 0)
                    {
                        sb1.AppendFormat(" Model_Hall = '{0}' ", str[i]);
                    }
                    else
                    {
                        sb1.AppendFormat(" OR Model_Hall = '{0}' ", str[i]);
                    }
                }
                sb1.AppendFormat(" ) ");
            }
            
              //   if (!string.IsNullOrEmpty(model_Hall))
              //   {
              //       sb1.AppendFormat(" AND (Model_Hall = '{0}')", model_Hall);
              //   }
            //日期
            if (!string.IsNullOrEmpty(strDayType))
            {
                if (!string.IsNullOrEmpty(strDayBegin))
                {
                    sb1.AppendFormat(" AND ({0} >= '{1}')", (strDayType == "10") ? "ServiceTime" : "Adddate", strDayBegin);
                }

                if (!string.IsNullOrEmpty(strDayEnd))
                {
                    sb1.AppendFormat(" AND ({0} <= '{1}')", (strDayType == "10") ? "ServiceTime" : "Adddate", DateTime.Parse(strDayEnd).AddDays(1));
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(strDayBegin))
                {
                    sb1.AppendFormat(" AND ({0} >= '{1}')", "Adddate", strDayBegin);
                }

                if (!string.IsNullOrEmpty(strDayEnd))
                {
                    sb1.AppendFormat(" AND ({0} <= '{1}')", "Adddate", DateTime.Parse(strDayEnd).AddDays(1));
                }
            }
            //面积
            if (!string.IsNullOrEmpty(buildingAreaStart))
                sb1.AppendFormat(" AND (BuildingArea >= {0})", buildingAreaStart);
            if (!string.IsNullOrEmpty(buildingAreaEnd))
                sb1.AppendFormat(" AND (BuildingArea <= {0})", buildingAreaEnd);
            //用途
            if (!string.IsNullOrEmpty(strHouseUse))
                sb1.AppendFormat(" AND (HouseUse = '{0}')", strHouseUse);
            //类型
            if (!string.IsNullOrEmpty(strBuildingType))
                sb1.AppendFormat(" AND (BuildingType = '{0}')", strBuildingType);
            //备案
            if (!string.IsNullOrEmpty(isMarked)) 
                sb1.AppendFormat(" AND (IsMarked = {0})", isMarked);
            //保护
            if (!string.IsNullOrEmpty(isPhoneProtected))
            {
                if ("1".Equals(isPhoneProtected))
                    sb1.AppendFormat(" AND (IsProtectPhone = {0}) ", 1);
                else if ("2".Equals(isPhoneProtected)) {
                    sb1.AppendFormat(" AND (IsProtectPhone = {0} AND IsAutoProPhone = {1}) ", 1, 1);
                }
                else if ("3".Equals(isPhoneProtected)) {
                    sb1.AppendFormat(" AND (IsProtectPhone = {0} AND IsAutoProPhone = {1}) ", 1, 0);
                } else {
                    sb1.AppendFormat(" AND (IsProtectPhone = {0}) ", 0);
                }
                
            }
            //装修
            if (!string.IsNullOrEmpty(fitment))
                sb1.AppendFormat(" AND (Fitment = '{0}')", fitment);
            //钥匙
            if (!string.IsNullOrEmpty(isHavekey))
            {
                if ("10".Equals(isHavekey))
                    sb1.AppendFormat(" AND (IsHavekey = '{0}')", 1);
                else
                    sb1.AppendFormat(" AND (IsHavekey = '{0}')", 0);
            }
            //工号
            if (!string.IsNullOrEmpty(strUserCode))
            {
                Chenxin.Lib.Passport.Entity.Hr_UserInfo hr = Chenxin.Lib.Passport.DAL.Hr_UserInfo.GetEntityByCode(strUserCode);
                if (hr != null)
                {
                    sb1.AppendFormat(" AND OprPersonId='{0}'", hr.UserId);
                }
                else
                {
                    sb1.AppendFormat(" AND (1=0)");
                }
                hr = null;
            }
            //楼层
            if (!string.IsNullOrEmpty(floorStart))
                sb1.AppendFormat(" AND (Cur_Floor >= {0})", floorStart);
            if (!string.IsNullOrEmpty(floorEnd))
                sb1.AppendFormat(" AND (Cur_Floor <= {0})", floorEnd);
            
            //描述：快速搜索参数拼接
            if (context.Request["quicktype"] != null)
            {
                switch (context.Request["quicktype"])
                {
                    case "owner"://我的房源
                        sb1.AppendFormat(" And(OprPersonId='{0}')", CurrentUserInfo.UserId);
                        break;
                    case "depart"://本店房源
                        sb1.AppendFormat(" And(OprDepartId='{0}')", CurrentUserInfo.DepartId);
                        break;
                    case "today"://本日房源
                        sb1.AppendFormat(" And (datediff(d,Adddate,'{0}')=0)", DateTime.Now);
                        break;
                    case "thismonth"://本月房源
                        sb1.AppendFormat(" And (datediff(m,Adddate,'{0}')=0)", DateTime.Now);
                        break;
                    case "key"://要是房源
                        sb1.Append(" And (IsHavekey='1')");
                        break;
                    case "favor":// 我的收藏
                        sb1.AppendFormat(" And (HouseId in (select FavorId from Personal_FavorsInfo where FavorPersonId = '{0}' and FavorType = 0 ))", CurrentUserInfo.UserId); 
                        break;
                }
            }
            
            //级联//////////////////////////////////////////////////////
            if (userId != Guid.Empty)
                sb1.AppendFormat(" AND (OprPersonId = '{0}') ", userId);
            else if (departId != Guid.Empty)
                sb1.AppendFormat(" AND (OprDepartId = '{0}')", departId);
            else if (areaId != Guid.Empty)
            {
                Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item = null;
                string strCachkey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, areaId);
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                item = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCachkey);
                if (!cs.Hit)
                {
                    item = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(areaId);
                    if (item != null) cs.Set(strCachkey, item, DateTime.Now.AddDays(1));
                }

                if (item == null) context.Response.Write(string.Format("{{success:'0',msg:'{0}',data:''}}", "获取商圈或分类数据丢失"));

                sb1.AppendFormat(" AND (OprDepartId in (select departId from v_Hr_DepartmentInfo where DepartSrc like '{0}%'))", item.DepartSrc);
            }
            else if (companyId != Guid.Empty)
                sb1.AppendFormat(" AND (CompanyId = '{0}')", companyId);
            else if (cityId != Guid.Empty)
                sb1.AppendFormat(" AND (CityId = '{0}')", cityId);
            else
                sb1.AppendFormat(" AND (CompanyId = '{0}')", CurrentUserInfo.CompanyId);
    

            //判断权限范围/////////////////////////////////////////////
            System.Text.StringBuilder sb2 = new System.Text.StringBuilder();
    
            bool IsPublicHouse;
            bool IsPrivateHouse;
            //公盘房源权限
            IsPublicHouse = CurrentUserInfo.ContainsPermit(Constants.Permit_ViewPublicHouse);
            //私盘房源权限
            IsPrivateHouse = CurrentUserInfo.ContainsPermit(Constants.Permit_ViewPrivateHouse);
            
            //所有房源权限
            if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewAllHouse))
            {
                //所有权限
                if (IsPublicHouse && IsPrivateHouse)
                {
                    sb2.Append(" 1=1 ");
                }
                //公盘房源权限
                else if (IsPublicHouse)
                {
                    sb2.AppendFormat(" (IsProtectHouse=0 Or OprPersonId = '{0}') ", CurrentUserInfo.UserId);
                }
                //私盘房源权限
                else if (IsPrivateHouse)
                {
                    sb2.AppendFormat(" (IsProtectHouse=1 Or OprPersonId = '{0}') ", CurrentUserInfo.UserId);
                }
                //无房源访问权限
                else
                {
                    sb2.AppendFormat(" OprPersonId = '{0}' ", CurrentUserInfo.UserId);
                }
            }
            //城市房源权限
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewCityHouse))
            {
                //所有权限
                if (IsPublicHouse && IsPrivateHouse)
                {
                    sb2.Append("(");
                    sb2.AppendFormat(" CityId='{0}' ", CurrentUserInfo.CityId.ToString());
                    sb2.AppendFormat(" Or OprPersonId = '{0}'", CurrentUserInfo.UserId);
                    sb2.Append(")");
                }
                //公盘房源权限
                else if (IsPublicHouse)
                {
                    sb2.Append("(");
                    sb2.AppendFormat(" (CityId='{0}' And IsProtectHouse=0) ", CurrentUserInfo.CityId.ToString());
                    sb2.AppendFormat(" Or OprPersonId = '{0}'", CurrentUserInfo.UserId);
                    sb2.Append(")");
                }
                //私盘房源权限
                else if (IsPrivateHouse)
                {
                    sb2.Append("(");
                    sb2.AppendFormat(" (CityId='{0}' And IsProtectHouse=1) ", CurrentUserInfo.CityId.ToString());
                    sb2.AppendFormat(" Or OprPersonId = '{0}'", CurrentUserInfo.UserId);
                    sb2.Append(")");
                }
                //无房源访问权限
                else
                {
                    sb2.AppendFormat("(OprPersonId = '{0}')", CurrentUserInfo.UserId);
                }
            }
            //公司房源权限
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewCompanyHouse))
            {
                //所有权限
                if (IsPublicHouse && IsPrivateHouse)
                {
                    sb2.Append("(");
                    sb2.AppendFormat(" CompanyId='{0}' ", CurrentUserInfo.CompanyId.ToString());
                    sb2.AppendFormat(" Or OprPersonId = '{0}'", CurrentUserInfo.UserId);
                    sb2.Append(")");
                }
                //公盘房源权限
                else if (IsPublicHouse)
                {
                    sb2.Append("(");
                    sb2.AppendFormat(" (CompanyId='{0}' And IsProtectHouse=0) ", CurrentUserInfo.CompanyId.ToString());
                    sb2.AppendFormat(" Or OprPersonId = '{0}'", CurrentUserInfo.UserId);
                    sb2.Append(")");
                }
                //私盘房源权限
                else if (IsPrivateHouse)
                {
                    sb2.Append("(");
                    sb2.AppendFormat(" (CompanyId='{0}' And IsProtectHouse=1) ", CurrentUserInfo.CompanyId.ToString());
                    sb2.AppendFormat(" Or OprPersonId = '{0}'", CurrentUserInfo.UserId);
                    sb2.Append(")");
                }
                //无房源访问权限
                else
                {
                    sb2.AppendFormat("(OprPersonId = '{0}')", CurrentUserInfo.UserId);
                }
            }
            //部门房源权限 
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewDepartHouse))
            {
                sb2.Append("(EXISTS(");
                sb2.Append("Select 1 from v_Struct_UserDepartRelation M ");
                sb2.AppendFormat("WHERE (OprDepartId = M.Departid AND  M.Userid= '{0}') ", CurrentUserInfo.UserId);
                sb2.Append("AND ((IsProtectHouse = 1 AND M.ViewPrivHouse =1) OR ");
                sb2.Append("(IsProtectHouse = 0 AND M.ViewPubHouse =1))");
                sb2.AppendFormat(") Or (OprPersonId = '{0}'))", CurrentUserInfo.UserId);
            }
            //个人房源权限
            else
            {
                sb2.AppendFormat("(OprPersonId = '{0}')", CurrentUserInfo.UserId);
            }
            
            if (sb1.ToString().Trim() != "")sb2.Append(sb1);

          
            string order = string.Empty;
            if (string.IsNullOrEmpty(strOrderField))
            {
                order = " Adddate DESC ";
            } else {
                order = " " + strOrderField;
            }
            System.Data.DataSet dshouselist = Chenxin.Lib.House.DAL.House_BaseInfo.GetList(
                iPageIndex, iPageSize, order, "House_BaseInfo", sb2.ToString(), fieldlist, tablefieldlist, true);

            int count = (int)dshouselist.Tables[1].Rows[0][0];

            string strHtml ="";
            string[] key = strOrderField.Split(' ');
            if (!GetHouseListHtml(dshouselist, key[0], out strHtml))
            {
                responseJson = string.Format("{{success:'0',msg:'{0}',data:''}}", "生成HTML错误");
            }
            
            dshouselist.Dispose();
            dshouselist = null;
            
            System.Text.StringBuilder head = new System.Text.StringBuilder();
            head.Append("{");
            head.AppendFormat("icon:{{width:{0},head:'',inField:false}},", 40);
            head.AppendFormat("Region:{{width:{0},head:'{1}',sortable:true}},", 40, "区域");
            head.AppendFormat("Status:{{width:{0},head:'{1}',sortable:true}},", 40, "状态");
            head.AppendFormat("Name:{{width:{0},head:'{1}',sortable:true,sortField:'{2}'}},", 170, "楼盘/门号/房号", "Community,BuildingName,Room");
            head.AppendFormat("BusinessKind:{{width:{0},head:'{1}',sortable:true}},", 40, "交易");
            head.AppendFormat("BuildingArea:{{width:{0},head:'{1}',sortable:true}},", 55, "面积");
            head.AppendFormat("SalePrice_U:{{width:{0},head:'{1}',sortable:true}},", 60, "单价(元)");
            head.AppendFormat("SalePrice_T:{{width:{0},head:'{1}',sortable:true,sortField:'{2}'}},", 65, "总价", "SalePrice_T,RentPrice");
            head.AppendFormat("HouseStyle:{{width:{0},head:'{1}',sortable:true,sortField:'{2}'}},", 40, "房型", "Model_Room,Model_Hall,Model_Toilet");
            head.AppendFormat("Floor:{{width:{0},head:'{1}',sortable:true,sortField:'{2}'}},", 50, "楼层", "Cur_Floor");
            head.AppendFormat("OprDepart:{{width:{0},head:'{1}',sortable:true}},", 70, "部门");
            head.AppendFormat("OprPerson:{{width:{0},head:'{1}',sortable:true}},", 60, "业务员");

            if ("servicetime".Equals(key[0].ToLower()))
            {
                head.AppendFormat("ServiceTime:{{width:{0},head:'{1}',sortable:true}}", 70, "跟单时间", true);
            }
            else {
                head.AppendFormat("Adddate:{{width:{0},head:'{1}',sortable:true}}", 70, "建档时间", true);
            }
         	head.Append("}");

            responseJson = string.Format("{{success:'1',msg:'{0}',data:{{count:{1},html:'{2}',head:{3}}}}}", "成功", count, strHtml, head.ToString());
            context.Response.Write(responseJson);
        }
        catch(Exception ex)
        {
            responseJson = string.Format("{{success:'0',msg:'{0}',data:''}}", "未知错误:"+ ex.Message);
            context.Response.Write(responseJson);
        }
    }

    /// <summary>
    /// 根据参数中的房源ID查询房源跟单数据;
    /// 返回Json数据：{count:'30',data:'abc'}
    /// </summary>
    /// <param name="context"></param>
    private void GetHouseTraceList(HttpContext context)
    {
        Guid houseId = (string.IsNullOrEmpty(context.Request["houseid"])) ? Guid.Empty : new Guid(context.Request["houseid"]);
        string responseJson = "";
        try
        {
            if (houseId == Guid.Empty)
            {
                responseJson = string.Format("{{success:'0',msg:'{0}',data:''}}", "参数错误，房源标识丢失");
                context.Response.Write(responseJson);
                return;
            }

            int iPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            int iPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);//页记录数
            string fieldlist = "*";
            string fieldtablelist = "*";
            string orderfield = "House_TraceInfo.TraceTime desc";
            string strwhere = string.Format("(houseId='{0}' AND IsHide = 0 AND Status = 0)", houseId);

            System.Data.DataSet dshousetracelist = null;
            if (iPageIndex == 1)
            {
                //分页第一页从缓存中读取
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_TRACE + "." + iPageSize.ToString(), houseId);

                dshousetracelist = cs.GetDataSet(strCachKey);
                if (!cs.Hit)
                {
                    //若未命中。从查询数据库中读取
                    dshousetracelist = Chenxin.Lib.House.DAL.House_TraceInfo.GetList(
                        iPageIndex, iPageSize, orderfield, "House_TraceInfo", strwhere, fieldlist, fieldtablelist, true);

                    if (dshousetracelist != null && dshousetracelist.Tables[0].Rows.Count != 0) 
                        cs.Set(strCachKey, dshousetracelist, DateTime.Now.AddMinutes(10));
                }
            }
            else
            {
                dshousetracelist = Chenxin.Lib.House.DAL.House_TraceInfo.GetList(
                iPageIndex, iPageSize, orderfield, "House_TraceInfo", strwhere, fieldlist, fieldtablelist, true);
            }
            
            int count = (int)dshousetracelist.Tables[1].Rows[0][0];

            string strHtml = "";
            if (!GetHouseTraceListHtml(dshousetracelist, out strHtml))
            {
                responseJson = string.Format("{{success:'0',msg:'{0}',data:''}}", "生成HTML错误");
            }

            dshousetracelist.Dispose();
            dshousetracelist = null;
            responseJson = string.Format("{{success:'1',msg:'{0}',data:{{count:'{1}',data:'{2}'}}}}", "成功", count, strHtml);
            context.Response.Write(responseJson);
        }
        catch (Exception ex)
        {
            responseJson = string.Format("{{success:'0',msg:'{0}',data:''}}", "未知错误：" + ex.Message);
            context.Response.Write(responseJson);
            return;
        }
    }


    /// <summary>
    /// 获取展开层中需要房源数据。数据以实体转换成Json返回。
    /// </summary>
    /// <param name="context"></param>
    private void GetHouseInfo(HttpContext context)
    {
        Guid houseId = (string.IsNullOrEmpty(context.Request["houseid"])) ? Guid.Empty : new Guid(context.Request["houseid"]);
        string responseJson ="";
        try
        {
            if (houseId == Guid.Empty)
            {
                responseJson = string.Format("{{success:'0',msg:'{0}',data:''}}", "参数错误，房源标识丢失");
                context.Response.Write(responseJson);
                return;
            }

            Chenxin.Lib.House.Entity.House_BaseInfo item = null;
            //从缓存服务器读取房源信息
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
            //string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_HOUSEINFO, houseId);
            //item = cs.GetObject(strCachKey) as Chenxin.Lib.House.Entity.House_BaseInfo;
            //if (!cs.Hit)//若未命中
            //{
                item = Chenxin.Lib.House.BLL.House_BaseInfo.GetHouseInfoEntity(houseId.ToString());
            //    cs.Set(strCachKey, item, DateTime.Now.AddHours(1));
            //}
            
            if (item == null)
            {
                responseJson = string.Format("{{success:'0',msg:'{0}',data:''}}", "参数错误，找不到对应的房源");
                context.Response.Write(responseJson);
                return;
            }

            responseJson = string.Format("{{success:'1',msg:'成功',data:{{houseinfo:{0}}}}}",
                Chenxin.Lib.Utility.JsonHelp.Convert2Json(item));

            context.Response.Write(responseJson);
        }
        catch (Exception ex)
        {
            responseJson = string.Format("{{success:'0',msg:'{0}',data:''}}", "未知错误：" +ex.Message);
            context.Response.Write(responseJson);
            return;
        }
        
    }
    
    private bool GetHouseListHtml(System.Data.DataSet dslist,string orderKey, out string strHtml)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        
        foreach (System.Data.DataRow row in dslist.Tables[0].Rows)
        {
            DateTime dt1 = Convert.ToDateTime(Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ServiceTime", ""));
            DateTime dt2 = DateTime.Now;

            TimeSpan ts = dt2.Subtract(dt1);

            if (ts.Days > Chenxin.Lib.Utility.Constants.UnTraceMaxDay && Chenxin.Lib.Utility.Constants.UnTraceMaxDay!=0)
                sb.AppendFormat("<dl id=\"{0}\" class=\"redword\">", row["HouseId"].ToString());
            else
                sb.AppendFormat("<dl id=\"{0}\">", row["HouseId"].ToString());
            //图标列
            sb.AppendFormat("<dd>{0}{1}{2}</dd>",
                (Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "IsHavekey", false)) ? "<div class=\"keyshow\" title=\"有钥匙\"></div>" : "<div class=\"keyno\" title=\"无钥匙\" ></div>",
                (Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "IsMarked", false)) ? "<div class=\"bashow\" title=\"已备案\"></div>" : "<div class=\"bano\" title=\"未备案\"></div>",
                (Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "IsProtectPhone", false)) ? "<div class=\"bhshow\" title=\"已保护\" ></div>" : "<div class=\"bhno\" title=\"未保护\" ></div>");
            //区域列
            sb.AppendFormat("<dd style=\"text-align:center;\" title=\"{0}\">{0}</dd>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Region", ""));
            //状态列
            sb.AppendFormat("<dd style=\"text-align:center;\" title=\"{0}\">{0}</dd>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Status", ""));
            //楼盘/门号/房号
            sb.AppendFormat("<dd title=\"{1}{2}{3}\"><a  href=\"ShowDetailInfo.aspx?houseid={0}\" target=\"blank\">{1} {2} {3}</a></dd>",
                                    DatasetHelper.GetValue(row, "HouseId", Guid.Empty), DatasetHelper.GetValue(row, "Community", ""),
                                    DatasetHelper.GetValue(row, "BuildingName", ""),
                                    DatasetHelper.GetValue(row, "Room",""));
            //交易列
            sb.AppendFormat("<dd style=\"text-align:center;\" title=\"{0}\">{0}</dd>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "BusinessKind", ""));
            //面积
            sb.AppendFormat("<dd style=\"text-align:right;\" title=\"{0:f2}\">{0:f2}</dd>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "BuildingArea", ""));
            //单价
            sb.AppendFormat("<dd style=\"text-align:right;\" title=\"{0:f0}\">{0:f0}</dd>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "SalePrice_U", 0f));
            //总价
            float price_t = Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "SalePrice_T", 0f);
            float price_u = Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "RentPrice", 0f);
            string kind = Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Kind", "");
            //出售
             if ("10".Equals(kind))
             {
                 sb.AppendFormat("<dd style=\"text-align:right;color:blue\" title=\"{0:f0}\">{0:f0}万</dd>", Math.Round(price_t / 10000.00));
             }
              //出租
             else if ("20".Equals(kind))
             {
                 sb.AppendFormat("<dd style=\"text-align:right;color:blue\" title=\"{0:f0}\">{0:f0}元</dd>", Math.Round(price_u));
             }
             // 租售
             else {
                 sb.AppendFormat("<dd style=\"text-align:right;color: blue\" title=\"{0:f0}\">{0:f0}万</dd>", Math.Round(price_t / 10000.00));
             }
             //房型
             string Model_Room = Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Model_Room", "-");
             string Model_Hall = Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Model_Hall", "-");
             string Model_Toilet = Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Model_Toilet", "-");
             string housestyle = Model_Room + "/" + Model_Hall + "/" + Model_Toilet;
             sb.AppendFormat("<dd style=\"text-align:center;\" title=\"{0}\">{0}</dd>", housestyle);
             //楼层
             string Cur_Floor = Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Cur_Floor", "-");
             string Total_Floor = Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Total_Floor", "-");
             sb.AppendFormat("<dd style=\"text-align:center;\" title=\"{0}\">{0}</dd>", Cur_Floor + "/" + Total_Floor);
            //部门
             sb.AppendFormat("<dd style=\"text-align:center;\" title=\"{0}\">{0}</dd>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "OprDepart", ""));
            //业务员
             sb.AppendFormat("<dd style=\"text-align:center;\" title=\"{0}\">{0}</dd>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "OprPerson", ""));
            //跟盘时间
             if ("servicetime".Equals(orderKey.ToLower()))
            {
                sb.AppendFormat("<dd style=\"text-align:center;\" title=\"{0:yyyy-MM-dd}\">{0:yyyy-MM-dd}</dd>", Convert.ToDateTime(Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "ServiceTime", "")));
            } else {
                sb.AppendFormat("<dd style=\"text-align:center;\" title=\"{0:yyyy-MM-dd}\">{0:yyyy-MM-dd}</dd>", Convert.ToDateTime(Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Adddate", "")));
            }
            sb.Append("</dl>");
            
            
            
        }
        strHtml = sb.ToString();
        return true;
    }


    /// <summary>
    /// 生成房源跟单列表
    /// </summary>
    /// <param name="dslist"></param>
    /// <param name="strHtml"></param>
    /// <returns></returns>
    private bool GetHouseTraceListHtml(System.Data.DataSet dslist, out string strHtml)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        //sb.Append("<div class=\"infos intitss\"><span class=\"rb\"><b>跟单内容</b></span><span class=\"rbpsn\"><b>跟单人</b></span>");
        //sb.Append("<span class=\"rbtim\"><b>跟单时间</b></span></div>");

        foreach (System.Data.DataRow row in dslist.Tables[0].Rows)
        {
            sb.AppendFormat("<div class=\"infos\" title={0}> <span class=\"rb\">{0}</span><span class=\"rbpsn\">{1}</span><span class=\"rbtim\">{2:yyyy-MM-dd}</span> </div>",
                JsonHelp.Convert2Json(DatasetHelper.GetValue(row, "TraceContext", "")).Replace("'","\\'"),
                DatasetHelper.GetValue(row, "Tractor", "-") + "/" + DatasetHelper.GetValue(row, "Depart", "-"),
                DatasetHelper.GetValue(row, "TraceTime", DateTime.Today));
        }

        strHtml = sb.ToString();
        return true;
    }
 
    //*******************************************
    //功能概要       ：编辑房源主要字段权限
    //参数説明       ：Customer_BaseInfo
    //返回值説明     ：void
    //功能詳細       ：编辑房源主要字段权限
    //作成者         ：chen.yugong 
    //作成日         ：2010-05-20
    //修改者         ：
    //修改日         ：
    //*******************************************
    private bool checkKeyWords(Chenxin.Lib.House.Entity.House_BaseInfo model,int status)
    {
        bool bRet = false;
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        //自己的房源
        if (model.OprPersonId.Equals(CurrentUserInfo.UserId) || (status != -1))
        {
            bRet = true;

        }//部门级房源修改权限
        else if (CurrentUserInfo.ContainsPermit(Constants.Permit_EditHouse_Department))
        {
            sb.AppendFormat(" (Departid = '{0}' AND  Userid= '{1}') ", model.OprDepartId, CurrentUserInfo.UserId);
            System.Collections.Generic.List<Chenxin.Lib.Hr.Entity.Struct_UserDepartRelation> list = Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.GetListArray(sb.ToString());

            if (list.Count > 0)
            {
                bRet = ((Chenxin.Lib.Hr.Entity.Struct_UserDepartRelation)list[0]).EditPrimaryHouse;
            }
            else
            {
                bRet = false;
            }
        } else {
            //修改主要字段权限
            if (CurrentUserInfo.ContainsPermit(Constants.Permit_EditPrKey))
            {
                bRet = true;
            } else {
                bRet = false;
            }
        
        }
        return bRet;
    }

    //*******************************************
    //功能概要       ：各功能单独权限判断
    //参数説明       ：context 请求上下文
    //               ：strMsg 响应消息
    //返回值説明     ：bool
    //功能詳細       ：各功能单独权限判断
    //作成者         ：he.jifeng
    //作成日         ：2010-06-13
    //*******************************************
    public override bool CustomerCheckPermint(HttpContext context, out string strMsg)
    {
        string op = context.Request.Params["op"];
        bool bRet = false;
        if (op != null)
        {
            op = op.ToLower();
            System.Collections.Hashtable per = new System.Collections.Hashtable();
            System.Collections.Hashtable confine = new System.Collections.Hashtable();

            if (op.Equals("edit") | (op.Equals("checkpermit") && "edit".Equals(context.Request.Params["code"])))
            {
                Chenxin.Lib.House.Entity.House_BaseInfo entUpdHouse = (Chenxin.Lib.House.Entity.House_BaseInfo)JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.House_BaseInfo));

                Chenxin.Lib.House.Entity.House_BaseInfo entHouseBase = Chenxin.Lib.House.DAL.House_BaseInfo.GetModel(entUpdHouse.HouseId);
                if (entHouseBase == null)
                {
                    strMsg = "{success:0,msg:'数据已变更,请刷新后重新执行操作！',data:''}";
                    return false;
                }

                //权限项
                per.Add("ALL", Constants.Permit_EditHouse_All);
                per.Add("CITY", Constants.Permit_EditHouse_City);
                per.Add("COMPANY", Constants.Permit_EditHouse_Company);
                per.Add("DEPART", Constants.Permit_EditHouse_Department);

                //加入范围
                confine.Add("CityId", entHouseBase.CityId);
                confine.Add("CompanyId", entHouseBase.CompanyId);
                confine.Add("OperatorId", entHouseBase.OprPersonId);

                //检查层级权限
                bRet = CheckPermint(per, confine, chkDepartPermit(entHouseBase, "edit"), out strMsg);
            }
            else
            {
                strMsg = "{success:1,msg:'',data:{permit:true}}";
                bRet = true;
            }
        }
        else
        {
            strMsg = "{success:0,msg:'参数有误！',data:''}";
            bRet = false;
        }
        return bRet;
    }
    //*******************************************
    //功能概要       ：判断编辑部门权限
    //参数説明       ：entBaseInfo 上下文
    //               ：op 操作类型
    //返回值説明     ：bool
    //功能詳細       ：部门内有无编辑房源权限
    //作成者         ：he.jifeng 
    //作成日         ：2010-06-13
    //修改者         ：
    //修改日         ：
    //*******************************************
    public bool chkDepartPermit(Chenxin.Lib.House.Entity.House_BaseInfo entBaseInfo, string op)
    {
        if (entBaseInfo.OprPersonId.Equals(CurrentUserInfo.UserId))
            return true;
        bool bRet = false;
        //检查有无权限
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.AppendFormat(" (Departid = '{0}' AND  Userid= '{1}') ", entBaseInfo.OprDepartId, CurrentUserInfo.UserId);
        System.Collections.Generic.List<Chenxin.Lib.Hr.Entity.Struct_UserDepartRelation> list = Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.GetListArray(sb.ToString());
        if (list.Count > 0)
        {
            Chenxin.Lib.Hr.Entity.Struct_UserDepartRelation struct_UserDepartRelation = list[0];

            switch (op)
            {
                case "edit":
                    bRet = (struct_UserDepartRelation.EditPrimaryHouse || struct_UserDepartRelation.EditNormalHouse);
                    break;
                default :
                    bRet = true;
                    break;
            }
        }
        return bRet;
    }

    //*******************************************
    //功能概要       ：通过客户ID获取房源ID
    //参数説明       ：context 上下文
    //返回值説明     ：房源ID
    //功能詳細       ：通过客户ID获取房源ID
    //作成者         ：he.jifeng 
    //作成日         ：2010-07-30
    //修改者         ：
    //修改日         ：
    //*******************************************
    private void GetHouseIdByCustomerId(HttpContext context)
    {
        string strRet = string.Empty;

        string strParam = context.Request.Params["CustomerId"];
        if (string.IsNullOrEmpty(strParam))
        {
            strRet = retExecResult(Constants.ExecResult.Error, "参数有误", "");
        }
        else
        {
            string strHouseId = Chenxin.Lib.House.BLL.House_BaseInfo.GetHouseIdByCustomerId(strParam);

            strRet = retExecResult(Constants.ExecResult.Succ, "", strHouseId);
        }
        context.Response.Write(strRet);
    }
}